<template>
  <div>
    <el-upload ref="uploadRef" v-model:file-list="fileList" class="avatar-uploader" :class="{ hide_box: isHidden }"
      list-type="picture-card" :limit="limit" :disabled="disabled" :auto-upload="autoUpload"
      accept="image/jpeg,image/png" :http-request="handleUploadImg" :on-change="handleChangeImg"
      :on-preview="handlePreview" :on-remove="handleRemove">
      <el-icon class="avatar-uploader-icon">
        <Plus />
      </el-icon>
    </el-upload>
    <el-image-viewer v-if="showImagePreview" @close="handleClosePreview" :url-list="imgPreviewList" />
  </div>
</template>
<script setup lang="ts">
import { ref, watch, watchEffect } from "vue";
import { ElMessage } from "element-plus";
import { uploadFileApi } from "@/api/user";
const props = defineProps({
  imgList: {
    type: Array,
    default: () => []
  },
  limit: {
    type: Number,
    default: 1
  },
  disabled: {
    type: Boolean,
    default: false
  },
  watermark: {
    type: Boolean,
    default: false
  },
  autoUpload: {
    type: Boolean,
    default: true
  },
  callBack: {
    type: Function,
    default: () => { }
  }
});
const emits = defineEmits(["success", "remove"]);

const uploadRef = ref();
const fileList = ref<any[]>([]);
const handleChangeImg = (params: any) => {
  const { size } = params;
  if (size > 1024 * 1024 * 10) {
    ElMessage.error("图片大小不能超过 10MB!");
  }
  fileList.value.pop();
};
// 上传图片
const handleUploadImg = () => {
  let uploadPromise = fileList.value.map((item) => {
    return new Promise((resolve, reject) => {
      if (!item.raw) {
        resolve(item.url);
        return;
      }
      const formData = new FormData();
      formData.append("file", item.raw);
      if (props.watermark) {
        formData.append("type", "1");
      }
      uploadFileApi(formData)
        .then((res: any) => {
          resolve(res[0].accessUrl);
        })
        .catch((error) => {
          reject(error);
        });
    });
  });
  Promise.all(uploadPromise).then((res) => {
    fileList.value = res.map((item: any) => {
      return { url: item };
    });
    emits("success", fileList.value);
  });
};

// 预览
const showImagePreview = ref(false);
const imgPreviewList = ref<any[]>([]);
const handlePreview = (list: any) => {
  imgPreviewList.value = [list.url];
  handleClosePreview();
};
const handleClosePreview = () => {
  showImagePreview.value = !showImagePreview.value;
};

// 删除
const handleRemove = (file: any) => {
  fileList.value = fileList.value.filter((item: any) => item.uid !== file.uid);
  emits("remove", fileList.value);
};

// 上次按钮是否隐藏
const isHidden = ref(false);
// 当上传图片数量大于限制数量时隐藏上传按钮
watchEffect(() => {
  if (fileList.value.length >= props.limit) {
    isHidden.value = true;
  } else {
    isHidden.value = false;
  }
});
watch(() => props.imgList, () => {
  fileList.value = props.imgList;
});

watch(fileList, (newVal, oldVal) => {
  props.callBack(newVal, oldVal)
})

defineExpose({ handleManualUpload: handleUploadImg });
</script>
<style scoped lang="scss">
.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
  border-radius: 6px;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
  box-sizing: border-box;
}

:deep(.el-upload-list__item) {
  width: 100px;
  height: 100px;
  box-sizing: border-box;
}

.hide_box :deep(.el-upload--picture-card) {
  display: none;
}
</style>
